package blackberry.util.field;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.UiEngine;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

abstract public class DjDialog extends PopupScreen implements FieldChangeListener{

	private int MaxWidthOfButtons = 0;
	
	private int initIndex;
	private ButtonField[] buttonArray;//포커스를 이동하기위해 배열로 저장해둠
	
	public DjDialog(String message, String[] buttonNames, int initIndex) {
		super(new VerticalFieldManager());
		
		add(new LabelField(message));
		
		buttonArray = new ButtonField[buttonNames.length];
		HorizontalFieldManager buttonManager = new HorizontalFieldManager(FIELD_RIGHT);
		for (int i = 0; i < buttonNames.length; i++) {

			UnificationButton button = new UnificationButton(buttonNames[i]);
			button.setChangeListener(this);
			buttonArray[i] = button;
			
			buttonManager.add(button);
		}
		add(buttonManager);
		
		this.initIndex = initIndex;
	}
	
	public void fieldChanged(Field field, int context) {
		close();
		buttonChanged(((ButtonField)field).getLabel());
	}
	
	public void pushDialog(){
		UiApplication.getUiApplication().pushScreen(this);
		buttonArray[initIndex].setFocus();
	}
	
	public void pushGlobalDialog(){
		UiApplication.getUiApplication().pushGlobalScreen(this, -9999, UiEngine.GLOBAL_SHOW_LOWER);
		buttonArray[initIndex].setFocus();
	}
	
	protected boolean keyUp(int keycode, int time) {
		if (Keypad.key(keycode) == Keypad.KEY_ESCAPE)
			close();
		return super.keyUp(keycode, time);
	}
	
	abstract public void buttonChanged(String buttonName);
	
	class UnificationButton extends ButtonField {
		
		public UnificationButton(String buttonName) {
			super(buttonName);
			if (MaxWidthOfButtons < super.getPreferredWidth())
				MaxWidthOfButtons = super.getPreferredWidth();
		}
		
		public int getPreferredWidth() {
			return MaxWidthOfButtons;
		}
		
		public int getPreferredHeight() {
			return super.getPreferredHeight();
		}
	}
}